package middleware

import (
	"encoding/json"
	"fmt"
	"gitee.com/sdzxq/api_server/conf"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"net/http"
)

func SingleTokenVerify() gin.HandlerFunc {
	return func(c *gin.Context) {

		token := c.DefaultQuery("Token","none")
		if token == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"message":"Token不能为空",
			})
			c.Abort()
			return
		}

		if res := ParseOneToken(token); res {
			// log some information necessary.
			c.Next()
		} else {
			c.JSON(http.StatusUnauthorized, gin.H{
				"success": false,
				"message": "can't pass without the right token",
			})
			c.Abort()
			return
		}

	}
}



func ParseOneToken(token string) bool {
	token1, err := jwt.Parse(token, func(token1 *jwt.Token)(interface{}, error){
		return []byte(conf.Secret),nil
	})
	if err != nil {
		fmt.Println(err)
		return false
	}
	if token1.Valid {
		_, err := json.Marshal(token1)
		if err != nil {
			fmt.Println(err)
			return false
		}
		fmt.Println("up here is a Claim structure")
		return true
	}else {
		fmt.Println("token is not valid!")
		return false
	}
}